package com.xdemo.personal.fileupload;

import java.io.File;

import org.apache.commons.fileupload.disk.DiskFileItem;

import com.xdemo.algorithm.CommonShortUrlGenerator;
import com.xdemo.algorithm.IShortUrlGenerator;
import com.xdemo.model.ShortUrl;
import com.xdemo.personal.manager.DaoManager;
import com.xdemo.personal.server.pool.EManager;
import com.xdemo.personal.server.pool.ManagerPool;

public class SimpleFileProcessor implements IFileProcessor {

	private IShortUrlGenerator shortUrlGenerator;
	
	public SimpleFileProcessor() {
		shortUrlGenerator = new CommonShortUrlGenerator();
	}
	
	@Override
	public ShortUrl processorFile(IFileStore store,DiskFileItem diskItem) {
		String _originName = diskItem.getName();
		String _fileType = "";
		if(_originName.lastIndexOf('.') != -1) {
			_fileType = _originName.substring(_originName.lastIndexOf('.'));
		}
		File _file = store.getFreshFileToStore(_fileType);
		if(_file == null) {
			return null;
		}
		try {
			diskItem.write(_file);
			String _shortUrl = shortUrlGenerator.shortUrl(_file.getName());
			DaoManager _daoManager = (DaoManager)ManagerPool.getManager(EManager.DAO);
			ShortUrl _url = new ShortUrl();
			_url.setUrl(_shortUrl);
			_url.setFileName(_file.getName());
			_url.setLocation(_file.getAbsolutePath());
			_daoManager.getShortUrlDao().save(_url);
			return _url;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
